//
//  Striing+Ext.swift
//  TTProduct
//
//  Created by Toj on 1/14/21.
//

import Foundation
import CoreGraphics

public extension String {
    
    /** 分割成数组
     - parameter separator: 分割符
     - returns: 分割的数组
     */
    func cm_split(_ separator: String) -> [String] {
        return components(separatedBy: CharacterSet(charactersIn:separator))
    }
    
    func st_split(by separator: String) -> (key: String, value: String) {
        guard var fIndex = firstIndex(of: Character(separator)) else { return ("", "") }
        
        var subString = self[..<fIndex]
        let key = String(subString)
        
        fIndex = index(fIndex, offsetBy: 1)
      
        subString = self[fIndex...]
        let value = String(subString)
        
        return (key, value)
    }
    
    /** 去除左右空格 */
    var cm_trim: String {
        return trimmingCharacters(in: .whitespaces)
    }
    
    func cm_trim(string: String = " ") -> String {
        let character = CharacterSet(charactersIn: string)
        return trimmingCharacters(in: character)
    }
    
    /** 替换字符
     - parameter string:        要被替换的字符串
     - parameter replaceString: 替换成的字符串
     - returns: 被替换过后的新字符串
     */
    func cm_replace(_ string: String, _ replaceString: String) -> String {
        return replacingOccurrences(of: string, with: replaceString)
    }
    
    /** 如果字符串的位数不够length长度, 左补齐padding字符
     - parameter length :   一共长度
     - parameter padding: 补齐的字符
     - returns: 返回totalLength长度的字符
     */
    mutating func cm_leftPadding(length: Int, padding: String) {
        for _ in count..<length {
            self =+ padding
        }
    }
    
    /** 如果字符串的位数不够length长度, 右补齐padding字符
     - parameter length :   一共长度
     - parameter padding: 补齐的字符
     - returns: 返回totalLength长度的字符
     */
    mutating func cm_rightPadding(length: Int, padding: String) {
        for _ in count..<length {
            self += padding
        }
    }
    
    /** 路径拼接
     - parameter component: 路径部分名称
     - returns: 被替换过后的新字符串
     */
    func cm_appending(path component: String) -> String {
        let path = self as NSString
        return path.appendingPathComponent(component)
    }
    
    mutating func cm_append(path component: String) {
       
        self = cm_appending(path: component)
    }
}
